package models;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import play.db.jpa.Model;
import util.PageUtil;

@Entity
@Table(name = "tradeproductlist")
public class TradeProductList extends Model {

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "product_id")
	public Product product;
	
	
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "trade_id")
	public Trade trade;

	public TradeProductList() {
	}

	public TradeProductList(Product product, Trade trade) {
		this.product = product;
		this.trade = trade;
	}
	
	
	public static List<TradeProductList> getTrade(int pageNum, int pageSize,long typeID){
		
		String hql=" from TradeProductList productList " +
				   " inner join fetch productList.trade " +
				   " inner join fetch productList.product " +
				   " inner join fetch productList.product.types " +
				   " where productList.product.types.id=? ";
		
		return find(hql,typeID).from(PageUtil.getPageBegin(pageNum,pageSize)).fetch(pageSize);
	}
	
	public static long getTypesCount(long typeID){
		
		String hql=" from TradeProductList productList " +
				   " inner join  productList.trade " +
				   " inner join  productList.product " +
				   " inner join  productList.product.types " +
				   " where productList.product.types.id=? ";

		long count = TradeProductList.count(hql, typeID);
		return count;
	}
	
	public static TradeProductList detail(long typeID){
		
		String hql=" from TradeProductList tpl " +
				   " inner join fetch tpl.trade trade " +
				   " inner join fetch trade.member" +
				   " inner join fetch tpl.product product " +
				   " inner join fetch product.types" +
				   " where tpl.id=?";
		return TradeProductList.find(hql, typeID).first();
	}
	
	public static List<TradeProductList> findByMemberID(long memberid,int limit){
		
		String hql=" from TradeProductList tpl " +
				   " inner join fetch tpl.trade trade " +
				   " inner join fetch trade.member mem" +
				   " inner join fetch tpl.product product " +
				   " inner join fetch product.types" +
				   " where mem.id=? order by trade.time desc ";
		
		List<TradeProductList> result=null;
		if(limit>0){
			result=TradeProductList.find(hql, memberid).fetch(limit);
		}else{
			result=TradeProductList.find(hql, memberid).fetch();
		}
		return result;
	}
	
	

}